# !/usr/bin/python3
import hashlib

import pymysql


class DB(object):
    def __init__(self):
        try:
            self.con = pymysql.connect(
                host='8.130.29.43',
                port=3306,
                user='root',
                passwd='zj20020427',
                db='BlueSpace',  # 数据库名
                charset='utf8'
            )
        except pymysql.Error as e:
            print("Error %d：%s" % (e.args[0], e.args[1]))
            exit()
        self.cursor = self.con.cursor()  # 创建游标对象

    # 增加信息
    def add_data(self, sql, data=[]):
        try:
            self.cursor.execute(sql, data)
            self.con.commit()
        except Exception as e:
            self.con.rollback()
            print("Error", e.args[0])

    # 修改或删除信息
    def update_or_delete(self, sql):
        try:
            self.cursor.execute(sql)
            self.con.commit()
        except Exception as e:
            self.con.rollback()
            print("Error ", e.args[0])

    # 查询一条信息
    def search_one(self, sql):
        try:
            self.cursor.execute(sql)
            res = self.cursor.fetchone()
        except Exception as e:
            return "Error " + e.args[0]
        return res

    # 查看用户是否是注册用户，返回布尔值
    def is_user(self, key):
        try:
            self.cursor.execute(f"select * from Users where user_key='{key}';")
            res = self.cursor.fetchone()  # 查看返回
            if res != None:  # 存在返回
                return True
            else:
                return False
        except Exception as e:
            # return "Error " + e.args[0]
            return False

    # 从key中得到用户
    def get_user(self, key):
        try:
            self.cursor.execute(f"SELECT ID FROM Users WHERE user_key='{key}';")
            res = str(self.cursor.fetchone())[1:-2]
        except Exception as e:
            return "Error " + e.args[0]
        return res

    # 创建一条位置记录
    def insert_locations(self, ID, data=None):
        if data is None:
            data = []
        try:
            sql = f"INSERT INTO BlueSpace.{ID}_location VALUES(NULL,%s,%s,%s,%s,%s)"
            self.cursor.execute(sql, data)
            self.con.commit()
        except Exception as e:
            self.con.rollback()
            print("Error", e.args[0])

    # 关闭游标和数据库的连接
    def __del__(self):
        self.cursor.close()
        self.con.close()

    # 创建一条通知记录（待完成且只能在通知调用后调用）


# 对用户key编码，查询是否为用户
def encode(password):
    # 创建一个SHA对象，指定使用SHA-256算法
    sha256 = hashlib.sha256()
    # 更新要加密的数据
    sha256.update(password.encode('utf-8'))
    # 获取加密后的十六进制字符串
    encrypted_data = sha256.hexdigest()
    return encrypted_data

# 实例化一个对象
# db = DB()
# db.create_locations(db.get_user('3c63d07e928a431200f5d57a9abed524aab6b3718198843564674167688b0932'))
# 插入一条数据
# data = ('小小', 60, '财经中学', '199999999', encode('N3JRbYPRAHzpST6'))
# db.add_data(data)
# 调用插入一条位置记录
# location_data = ('590.61392', '547.36846', '971.563', '2002-02-01 11:03:30', '0.09')
# db.insert_locations(db.get_user('T3FNWo9yJpcDTJ5jDZKxwpSoovmeItyVaEq9YxaeT4Yo5FO0wx'), location_data)
